package com.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.common.result.PageResult;
import com.crm.common.utils.StringUtils;
import com.crm.domain.Activity;
import com.crm.dto.ActivityPageQueryDTO;
import com.crm.mapper.ActivityMapper;
import com.crm.service.ActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements ActivityService {

    @Autowired
    private ActivityMapper activityMapper;
    /*
    * 新增活动
    * */
    @Override
    public void add(Activity activity) {
        // 生成 8 位随机活动编码（字母+数字）
        String code = generateRandomCode(8);
        activity.setCode(code);
        activity.setStatus("2");
        activityMapper.insert(activity);

    }
    /*
    * 分页查询
    * */
    @Override
    public PageResult page(ActivityPageQueryDTO queryDTO) {
        Page<Activity> actpage = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        LambdaQueryWrapper<Activity> wrapper = new LambdaQueryWrapper<>();

        wrapper
                .like(StringUtils.hasText(queryDTO.getCode()), Activity::getCode, queryDTO.getCode())
                .eq(StringUtils.hasText(queryDTO.getChannel()), Activity::getChannel, queryDTO.getChannel())
                .eq(StringUtils.hasText(queryDTO.getStatus()), Activity::getStatus, queryDTO.getStatus());

        // 处理时间范围（从 params Map 解析）
        Map<String, Object> params = queryDTO.getParams();

        if (params != null) {
            String beginCreateTime = params.get("beginCreateTime") != null ? params.get("beginCreateTime").toString() : null;
            String endCreateTime = params.get("endCreateTime") != null ? params.get("endCreateTime").toString() : null;

            if (StringUtils.hasText(beginCreateTime) && StringUtils.hasText(endCreateTime)) {
                wrapper.between(Activity::getCreateTime,
                        parseFlexible(beginCreateTime),
                        parseFlexible(endCreateTime));
            }

            String beginTime = params.get("beginTime") != null ? params.get("beginTime").toString() : null;
            String endTime = params.get("endTime") != null ? params.get("endTime").toString() : null;

            if (StringUtils.hasText(beginTime)) {
                wrapper.ge(Activity::getBeginTime, parseFlexible(beginTime));
            }

            if (StringUtils.hasText(endTime)) {
                wrapper.le(Activity::getEndTime, parseFlexible(endTime));
            }
        }


        wrapper.orderByDesc(Activity::getCreateTime);
        activityMapper.selectPage(actpage, wrapper);

        List<Activity> records = actpage.getRecords();
        long total = actpage.getTotal();

        Map<String, Object> stats = new HashMap<>();
        stats.put("total", total);
        stats.put("pass", records.stream().filter(a -> "2".equals(String.valueOf(a.getStatus()))).count());
        stats.put("reject", records.stream().filter(a -> "1".equals(String.valueOf(a.getStatus()))).count());
        stats.put("toAudit", records.stream().filter(a -> "0".equals(String.valueOf(a.getStatus()))).count());
        stats.put("finish", records.stream().filter(a -> "3".equals(String.valueOf(a.getStatus()))).count());

        return PageResult.success(total, records, stats);

    }
    private static LocalDateTime parseFlexible(String timeStr) {
        if (timeStr.length() == 10) {
            // 格式为 yyyy-MM-dd，补上时间 00:00:00
            return LocalDate.parse(timeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd"))
                    .atStartOfDay();
        } else {
            // 格式为 yyyy-MM-dd HH:mm:ss
            return LocalDateTime.parse(timeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        }
    }


    /*
    * 根据id查询互动
    * */
    @Override
    public Activity selectById(Integer id) {
        Activity activity = activityMapper.selectById(id);
        return activity;
    }

    /*
    * 根据id删除活动
    * */
    @Override
    public void deleteById(Long id) {
        activityMapper.deleteById(id);
    }

    /*
    * 修改活动
    * */
    @Override
    public void update(Activity activity) {
        activityMapper.updateById(activity);

    }

    @Override
    public List<Activity> listselect(Integer type) {
        LambdaQueryWrapper<Activity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Activity::getType,type);
        return activityMapper.selectList(wrapper);
    }


    /*
    * 随机生成8位编码
    * */
    private String generateRandomCode(int length) {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            sb.append(chars.charAt(random.nextInt(chars.length())));
        }
        return sb.toString();
    }

}
